package sf.database.dialect.db;

import sf.database.dialect.Keywords;
import sf.database.meta.TableMapping;
import sf.database.util.DBUtils;
import sf.querydsl.QueryDSLSupportDatabase;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * sqlserver2005
 */
public class SQLServer2005Dialect extends SqlServerDialect {

    @Override
    public String getQueryDslDialect() {
        return QueryDSLSupportDatabase.SQLServer2005;
    }

    public SQLServer2005Dialect() {
        this.keywords.addAll(Keywords.SQLSERVER2005);
    }

    @Override
    public StringBuilder sqlPageList(StringBuilder sb, long offset, int limit) {
        long pageEnd = offset + limit - 1;
        String sql = sb.toString();
        sql = sql.replaceFirst("(?i)select(\\s+distinct\\s+)?", "$0 top(" + pageEnd + ") ");

        int capacity = sql.length() + 190;
        StringBuilder builder = new StringBuilder(capacity);
        builder.append("with query as ( select inner_query.*, row_number() over (order by current_timestamp) as rn from ( ");
        builder.append(sql);
        builder.append(" ) inner_query ) select * from query where rn between ");
        builder.append(offset).append(" and ").append(pageEnd);

        return builder;
    }

    public List<String> getIndexNames(TableMapping en, Connection conn) {
        List<String> names = new ArrayList<String>();
        String showIndexs = "SELECT i.name FROM sys.indexes AS i "
                + "INNER JOIN sys.tables AS o ON i.[object_id] = o.[object_id] "
                + "WHERE  o.name = '" + en.getTableName() + "' AND i.is_primary_key = 0";
        PreparedStatement ppstat = null;
        ResultSet rest = null;
        try {
            ppstat = conn.prepareStatement(showIndexs);
            rest = ppstat.executeQuery();
            while (rest.next()) {
                String index = rest.getString(1);
                names.add(index);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtils.closeQuietly(rest);
            DBUtils.closeQuietly(ppstat);
        }
        return names;
    }
}
